package com.ktjiaoyu.ktmall.dao.impl;

import com.ktjiaoyu.ktmall.dao.BaseDao;
import com.ktjiaoyu.ktmall.dao.CartDao;
import com.ktjiaoyu.ktmall.entity.Cart;
import com.ktjiaoyu.ktmall.utils.DatabaseUtil;
import com.ktjiaoyu.ktmall.vo.CartVo;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CartDaoImpl extends BaseDao implements CartDao {
    public CartDaoImpl() {

    }
    public CartDaoImpl(Connection connection){
        super(connection);
    }

    @Override
    public List<CartVo> selectByUserId(String userId) {
        String sql = "SELECT c.*,p.title,p.main_image AS mainImage,p.price"+
                "FROM kt_cart c"+
                "LEFT JOIN kt_product p ON c.product_id = p.id"+
                "WHERE c.user_id = ?";
        try{
            return executeQuery(sql,rs->{
                List<CartVo> list=new ArrayList<>();
                try{
                    while(rs.next()){
                        list.add(readCartVo(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return list;
            },userId);
        }catch (SQLException e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public List<CartVo> selectByIds(List<String> cartIds) {
        if (cartIds == null || cartIds.isEmpty()) {
            return new ArrayList<>();
        }
        String placeholders = String.join(",", Collections.nCopies(cartIds.size(), "?"));
        String sql = "SELECT c.*,p.title,p.main_image AS mainImage,p.price"+
                "FROM kt_cart c"+
                "LEFT JOIN kt_product p ON c.product_id=p.id"+
                "WHERE c.id IN ("+placeholders+")";
        try{
            return executeQuery(sql,rs->{
                List<CartVo> list=new ArrayList<>();
                try{
                    while (rs.next()){
                        list.add(readCartVo(rs));
                    }
                }catch (SQLException e) {
                    e.printStackTrace();
                }
                return list;
            },cartIds.toArray());
        }catch (SQLException e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public Cart selectByUserAndProduct(String userId, String productId) {
        String sql = "SELECT id,user_id,product_id,quantity, selected,create_time,update_time FROM kt_cart WHERE user_id=? AND product_id=?";
        try{
            return executeQuery(sql,rs->{
                try{
                    if (rs.next()) {
                        return readCart(rs);
                    }
                }catch (SQLException e) {
                    e.printStackTrace();
                }
                return null;
            },userId,productId);
        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int insert(Cart cart) {
        String sql = "INSERT INTO kt_cart (user_id,product_id,quantity,selected) VALUES(?,?,?,?)";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            stmt.setString(1,cart.getUserId());
            stmt.setString(2,cart.getProductId());
            stmt.setInt(3,cart.getQuantity());
            stmt.setInt(4,cart.getSelected());
            int rows = stmt.executeUpdate();
            if (rows>0){
                rs=stmt.getGeneratedKeys();
                if (rs.next()) {
                    cart.setId(String.valueOf(rs.getLong(1)));
                    return rows;
                }
            }
            return 0;
        }catch (SQLException e){
            e.printStackTrace();
            return 0;
        }finally {
            DatabaseUtil.closeAll(conn,stmt,rs);
        }
    }

    @Override
    public int update(Cart cart) {
        String sql = "UPDATE kt_cart SET quantity=?,selected=?,"+"update_time=now() WHERE id=?";
        try{
            return executeUpdate(sql,cart.getQuantity(),cart.getSelected(),cart.getId());
        }catch (SQLException e){
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int countByUserId(String userId) {
        String sql = "SELECT COUNT(*) FROM kt_cart WHERE user_id=?";
        try{
            return executeQuery(sql,rs->{
                try{
                    if (rs.next()) {
                        return rs.getInt(1);
                    }
                }catch (SQLException e) {
                    e.printStackTrace();
                }
                return 0;
            },userId);
        }catch (SQLException e){
            e.printStackTrace();
            return 0;
        }
    }
    private CartVo readCartVo(ResultSet rs) throws SQLException {
        CartVo cartVo = new CartVo();
        cartVo.setId(rs.getString("id"));
        cartVo.setUserId(rs.getString("user_id"));
        cartVo.setProductId(rs.getString("product_id"));
        cartVo.setQuantity(rs.getInt("quantity"));
        cartVo.setSelected(rs.getInt("selected"));
        cartVo.setTitle(rs.getString("title"));
        cartVo.setMainImage(rs.getString("mainImage"));
        cartVo.setPrice(rs.getDouble("price"));
        return cartVo;
    }
    private Cart readCart(ResultSet rs) throws SQLException {
        Cart cart = new Cart();
        cart.setId(rs.getString("id"));
        cart.setUserId(rs.getString("user_id"));
        cart.setProductId(rs.getString("product_id"));
        cart.setQuantity(rs.getInt("quantity"));
        cart.setSelected(rs.getInt("selected"));
        cart.setCreateTime(rs.getDate("create_time"));
        cart.setUpdateTime(rs.getDate("update_time"));
        return cart;
    }
}
